<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>备份任务管理</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        h1, h2 { color: #333; }
        table { border-collapse: collapse; width: 100%; margin-top: 10px; }
        th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
        th { background-color: #f4f4f4; }
        tr:nth-child(even) { background-color: #f9f9f9; }
        input, select { width: 100%; box-sizing: border-box; padding: 6px; border: 1px solid #ccc; }
        button { padding: 8px 16px; background-color: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; margin-right: 5px; }
        button:hover { background-color: #0056b3; }
        .button-area { margin: 10px 0; }
        #message { margin-top: 10px; padding: 10px; border-radius: 4px; display: none; }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; display: block; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; display: block; }
        .loading { color: #007bff; }
        .detail-btn { background-color: #ffc107; color: #212529; }
        .detail-btn:hover { background-color: #e0a800; }
        .delete-btn { background-color: #dc3545; }
        .delete-btn:hover { background-color: #c82333; }
    </style>
</head>
<body>
<h1>备份任务管理</h1>

<!-- 操作按钮区域 -->
<div class="button-area">
    <button onclick="loadTaskList()">加载任务数据</button>
    <button onclick="saveTaskList()">保存任务数据</button>
</div>

<!-- 接口基础URL配置 -->
<div style="margin: 10px 0; color: #666;">
    <label for="baseUrl">接口基础URL: </label>
    <input type="text" id="baseUrl" value="http://localhost:8080" style="width: 300px;">
    <small>（根据你的后端服务地址修改）</small>
</div>

<!-- 备份任务数据表格 -->
<table>
    <thead>
    <tr>
        <th>任务名称 (name)</th>
        <th>任务类型 (type)</th>
        <th>开始时间 (startTime)</th>
        <th>结束时间 (endTime)</th>
        <th>是否更新 (isUpdate)</th>
        <th>状态 (status)</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="taskTableBody">
    <!-- 任务数据将在这里显示 -->
    </tbody>
</table>

<!-- 消息提示区域 -->
<div id="message"></div>

<script>
    let taskList = [];

    // 获取基础URL
    function getBaseUrl() {
        return document.getElementById("baseUrl").value.trim();
    }

    // 显示消息提示
    function showMessage(text, isError = false) {
        const messageEl = document.getElementById("message");
        messageEl.textContent = text;
        messageEl.className = isError ? "error" : "success";
        messageEl.style.display = "block";
        setTimeout(() => { messageEl.style.display = 'none'; }, 3000); // 3秒后自动隐藏
    }

    // 加载任务列表
    function loadTaskList() {
        const messageEl = document.getElementById("message");
        messageEl.textContent = "加载中...";
        messageEl.className = "loading";
        messageEl.style.display = "block";

        const url = `${getBaseUrl()}/base/equipment/v1/list2`;

        fetch(url)
            .then(response => {
                if (!response.ok) throw new Error(`加载失败: ${response.status} ${response.statusText}`);
                return response.json();
            })
            .then(data => {
                taskList = data;
                renderTable();
                showMessage(`加载成功，共 ${data.length} 条任务`);
            })
            .catch(error => {
                showMessage(`错误: ${error.message}`, true);
            });
    }

    // 保存任务列表
    function saveTaskList() {
        if (taskList.length === 0) {
            showMessage("没有数据可保存", true);
            return;
        }

        const messageEl = document.getElementById("message");
        messageEl.textContent = "保存中...";
        messageEl.className = "loading";
        messageEl.style.display = "block";

        const url = `${getBaseUrl()}/base/equipment/v1/save2`;

        fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(taskList)
        })
        .then(response => {
            if (!response.ok) throw new Error(`保存失败: ${response.status} ${response.statusText}`);
            return response.json();
        })
        .then(success => {
            showMessage(success ? "保存成功" : "保存失败（后端返回false）");
        })
        .catch(error => {
            showMessage(`错误: ${error.message}`, true);
        });
    }

    // 获取任务详情
    function getTaskDetail(name) {
        if (!name) {
            showMessage("任务名称不能为空", true);
            return;
        }

        const messageEl = document.getElementById("message");
        messageEl.textContent = "查询详情中...";
        messageEl.className = "loading";
        messageEl.style.display = "block";

        const url = `${getBaseUrl()}/base/equipment/v1/listDetail`;

        fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ name: name })
        })
        .then(response => {
            if (!response.ok) throw new Error(`查询失败: ${response.status} ${response.statusText}`);
            return response.json();
        })
        .then(detail => {
            // 格式化显示详情信息
            const detailText = `任务详情：名称=${detail.name}，类型=${detail.size}`;
            showMessage(detailText);
        })
        .catch(error => {
            showMessage(`错误: ${error.message}`, true);
        });
    }

    // 渲染表格数据
    function renderTable() {
        const tableBody = document.getElementById("taskTableBody");
        tableBody.innerHTML = ""; // 清空表格

        taskList.forEach((task, index) => {
            const row = tableBody.insertRow();

            // 为每个字段创建可编辑的单元格
            createEditableCell(row, task, 'name', 'text');
            createEditableCell(row, task, 'type', 'text');
            createEditableCell(row, task, 'startTime', 'datetime-local');
            createEditableCell(row, task, 'endTime', 'datetime-local');
            createEditableCell(row, task, 'isUpdate', 'select', [
                { value: 0, text: '否' },
                { value: 1, text: '是' }
            ]);
            createEditableCell(row, task, 'status', 'select', [
                { value: 0, text: '未执行' },
                { value: 1, text: '执行中' },
                { value: 2, text: '已完成' },
                { value: 3, text: '失败' }
            ]);

            // 操作列（详情+删除）
            const actionCell = row.insertCell();

            // 详情按钮
            const detailBtn = document.createElement("button");
            detailBtn.textContent = "详情";
            detailBtn.className = "detail-btn";
            detailBtn.onclick = () => {
                getTaskDetail(task.name);
            };
            actionCell.appendChild(detailBtn);

            // 删除按钮
            const deleteBtn = document.createElement("button");
            deleteBtn.textContent = "删除";
            deleteBtn.className = "delete-btn";
            deleteBtn.onclick = () => {
                taskList.splice(index, 1);
                renderTable();
            };
            actionCell.appendChild(deleteBtn);
        });

        // 添加一行用于新增任务
        addEmptyRow();
    }

    /**
     * 创建一个可编辑的表格单元格
     * @param {HTMLTableRowElement} row - 要添加单元格的行
     * @param {Object} task - 任务对象
     * @param {string} field - 字段名
     * @param {string} inputType - 输入框类型 ('text', 'datetime-local', 'select')
     * @param {Array<Object>} [options] - 当inputType为'select'时的选项列表
     */
    function createEditableCell(row, task, field, inputType, options) {
        const cell = row.insertCell();
        let input;

        if (inputType === 'select') {
            input = document.createElement("select");
            options.forEach(opt => {
                const option = document.createElement("option");
                option.value = opt.value;
                option.text = opt.text;
                // 设置默认选中值
                if (String(task[field]) === String(opt.value)) {
                    option.selected = true;
                }
                input.appendChild(option);
            });
            input.onchange = (e) => {
                task[field] = parseInt(e.target.value); // 对于select，值通常是整数
            };
        } else {
            input = document.createElement("input");
            input.type = inputType;
            // 格式化日期时间，使其符合 datetime-local 输入框的要求 (YYYY-MM-DDTHH:mm)
            input.value = inputType.includes('datetime') && task[field]
                ? task[field].replace(' ', 'T').slice(0, 16)
                : task[field] || '';

            input.onchange = (e) => {
                task[field] = e.target.value;
            };
        }
        cell.appendChild(input);
    }

    // 添加一行空数据用于新增
    function addEmptyRow() {
        const tableBody = document.getElementById("taskTableBody");
        const row = tableBody.insertRow();
        row.style.backgroundColor = "#e9f7ef"; // 给新增行一个不同的背景色

        // 为每个字段创建空的输入控件
        createEmptyInputCell(row, 'text', '任务名称');
        createEmptyInputCell(row, 'text', '任务类型');
        createEmptyInputCell(row, 'datetime-local', '');
        createEmptyInputCell(row, 'datetime-local', '');

        const isUpdateCell = row.insertCell();
        const isUpdateSelect = document.createElement("select");
        isUpdateSelect.innerHTML = `<option value="">-- 是否更新 --</option><option value="0">否</option><option value="1">是</option>`;
        isUpdateCell.appendChild(isUpdateSelect);

        const statusCell = row.insertCell();
        const statusSelect = document.createElement("select");
        statusSelect.innerHTML = `<option value="">-- 选择状态 --</option><option value="0">未执行</option><option value="1">执行中</option><option value="2">已完成</option><option value="3">失败</option>`;
        statusCell.appendChild(statusSelect);

        // 操作列（仅添加按钮）
        const actionCell = row.insertCell();
        const addButton = document.createElement("button");
        addButton.textContent = "确认添加";
        addButton.style.backgroundColor = "#28a745";
        addButton.onclick = () => {
            const inputs = row.querySelectorAll('input, select');
            const newTask = {
                name: inputs[0].value,
                type: inputs[1].value,
                startTime: inputs[2].value,
                endTime: inputs[3].value,
                isUpdate: inputs[4].value ? parseInt(inputs[4].value) : null,
                status: inputs[5].value ? parseInt(inputs[5].value) : null
            };

            // 简单校验
            if (!newTask.name || !newTask.type) {
                showMessage("任务名称和类型不能为空！", true);
                return;
            }

            taskList.push(newTask);
            renderTable();
        };
        actionCell.appendChild(addButton);
    }

    /**
     * 为新增行创建一个空的输入控件单元格
     */
    function createEmptyInputCell(row, inputType, placeholder) {
        const cell = row.insertCell();
        const input = document.createElement("input");
        input.type = inputType;
        input.placeholder = placeholder;
        cell.appendChild(input);
    }

</script>
</body>
</html>